<template>
  <div class="upload-container">
    <el-upload
      class="upload-area"
      drag
      :accept="acceptedFormats"
      :before-upload="beforeUpload"
      :http-request="handleUpload"
      :show-file-list="false"
      action="#"
    >
      <el-icon class="upload-icon"><upload-filled /></el-icon>
      <div class="upload-text">
        <span>拖拽图片到此处或点击上传</span>
        <p>支持 JPG、PNG、BMP 格式</p>
      </div>
    </el-upload>

    <div v-if="imageUrl" class="preview-container">
      <img :src="imageUrl" class="preview-image" />
      <div class="preview-actions">
        <el-button type="primary" @click="startColorization">开始上色</el-button>
        <el-button @click="resetUpload">重新上传</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import { colorizeImage } from '../api'

const emit = defineEmits(['upload-success', 'colorization-start'])

const acceptedFormats = '.jpg,.jpeg,.png,.bmp'
const imageUrl = ref('')
const uploadedFile = ref<File | null>(null)

const beforeUpload = (file: File) => {
  const isValidFormat = acceptedFormats.includes(file.name.substring(file.name.lastIndexOf('.')).toLowerCase())
  if (!isValidFormat) {
    ElMessage.error('请上传支持的图片格式！')
    return false
  }
  
  // 检查文件大小限制 (10MB)
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('图片大小不能超过 10MB!')
    return false
  }
  
  return true
}

const handleUpload = async (options: any) => {
  const file = options.file
  
  // 创建本地预览
  const reader = new FileReader()
  reader.onload = (e) => {
    imageUrl.value = e.target?.result as string
    uploadedFile.value = file
  }
  reader.readAsDataURL(file)
}

const startColorization = async () => {
  if (!uploadedFile.value) {
    ElMessage.warning('请先上传图片')
    return
  }
  
  emit('colorization-start', {
    originalImage: imageUrl.value,
    file: uploadedFile.value
  })
}

const resetUpload = () => {
  imageUrl.value = ''
  uploadedFile.value = null
}
</script>

<style scoped>
.upload-container {
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.upload-area {
  border: 2px dashed #dcdfe6;
  border-radius: 6px;
  padding: 20px;
  text-align: center;
}

.upload-icon {
  font-size: 48px;
  color: #409eff;
  margin-bottom: 10px;
}

.preview-container {
  margin-top: 20px;
  text-align: center;
}

.preview-image {
  max-width: 100%;
  max-height: 400px;
  object-fit: contain;
}

.preview-actions {
  margin-top: 20px;
}
</style> 